/* eslint-disable jsx-a11y/alt-text */
import React, { useEffect, useRef, useState } from 'react';
import {
  Breadcrumb,
  Button,
  Card,
  DatePicker,
  Form,
  message,
  Modal,
  Radio,
  // Select,
  Space,
  Table,
  Tag,
} from 'antd';
import { Link } from 'react-router-dom';
// import { getChannelApi } from 'api/channel';
import { delArticleByIdApi, getArticleDataApi } from 'api/article';
import Channel from 'components/Channel';

import defaultImgSrc from 'assets/error.png';

import {
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';

// const { Option } = Select;
const { RangePicker } = DatePicker;

export default function ArticleDist(props) {
  // 创建一个ref
  const fromDateRef = useRef();
  const pageInfoRef = useRef({});

  const articleStatus = [
    { id: -1, name: '全部', color: 'magenta' },
    { id: 0, name: '草稿', color: 'orange' },
    { id: 1, name: '待审核', color: 'red' },
    { id: 2, name: '审核通过', color: 'green' },
    { id: 3, name: '审核失败', color: 'cyan' },
  ];

  //筛选
  const onFinish = (values) => {
    // console.log(values);
    let fromDate = { ...values };
    // 移除fromDate.status属性
    if (fromDate.status === -1) delete fromDate.status;
    // 添加起始时间,结束时间
    if (fromDate.date) {
      fromDate.begin_pubdate = fromDate.date[0]
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss');
      fromDate.end_pubdate = fromDate.date[1]
        .endOf('day')
        .format('YYYY-MM-DD HH:mm:ss');
      delete fromDate.date;
    }

    //利用JSON的特性把对象中 的值为undefined的键给去掉
    // fromDate = JSON.parse(JSON.stringify(fromDate));
    console.log(fromDate);
    // 用ref保存表单数据
    fromDateRef.current = fromDate;

    // 发请求
    getArticleData(fromDate);
  };

  // //声明数据保存channel
  // const [channels, setChannels] = useState([]);
  // // 发送请求获取channels
  // const getChannels = async () => {
  //   const res = await getChannelApi();
  //   // console.log(res);
  //   setChannels(res.channels);
  // };
  // 声明文章列表
  const [articleDist, setArticleDist] = useState({});
  const getArticleData = async (params) => {
    let res = await getArticleDataApi(params);
    console.log(res);
    setArticleDist(res);
  };
  //挂载后的钩子
  useEffect(() => {
    // getChannels();
    getArticleData();
  }, []);

  // 分页功能
  const handlePageChange = (page, per_page) => {
    // console.log(page, per_page);
    pageInfoRef.current = { page, per_page };
    // 判断 fromDateRef.current是否为空
    let fromDate = fromDateRef.current || {};
    getArticleData({ page, per_page, ...fromDate });
  };

  // 删除
  const handleDelArticle = async (id) => {
    Modal.confirm({
      title: '温馨提示',
      icon: <ExclamationCircleOutlined />,
      content: '你确定要删除这篇文章？',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        console.log(id);
        await delArticleByIdApi(id);
        message.success('删除成功');

        // 判断 fromDateRef.current是否为空
        let fromDate = fromDateRef.current || {};

        // 删除最后一页的最后一条数据返回上一页
        // console.log('---1---', pageInfoRef.current);
        if (articleDist.results.length === 1 && articleDist.page > 1) {
          pageInfoRef.current.page -= 1;
        }
        // console.log('----2---', pageInfoRef.current);

        getArticleData({ ...pageInfoRef.current, ...fromDate });
      },
    });
  };

  // 编辑文章
  const handleEditArticle = (id) => {
    // console.log(id, props);
    props.history.push(`/edit/${id}`);
  };

  const columns = [
    {
      title: '封面',
      dataIndex: 'cover', //有dataIndex可以省略key属性
      render: (cover) => (
        // console.log(cover),
        <div style={{ width: '100px', height: '80px' }}>
          {
            <img
              style={{ width: '100%', height: '100%', objectFit: 'cover' }}
              src={cover.images[0] || defaultImgSrc}
            ></img>
          }
        </div>
      ),
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (status) => {
        // console.log(status);
        const currentItem = articleStatus.find((item) => item.id === status);
        return <Tag color={currentItem.color}>{currentItem.name}</Tag>;
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      key: 'handle',
      render: (value, record) => {
        // console.log(record);
        return (
          <Space>
            <Button
              shape="circle"
              type="primary"
              icon={<EditOutlined />}
              onClick={() => handleEditArticle(record.id)}
            />
            <Button
              shape="circle"
              danger
              icon={<DeleteOutlined />}
              onClick={() => handleDelArticle(record.id)}
            />
          </Space>
        );
      },
    },
  ];

  return (
    <Card
      title={
        <Breadcrumb>
          <Breadcrumb.Item>
            <Link to={'/home'}>首页</Link>
          </Breadcrumb.Item>
          <Breadcrumb.Item>文章列表</Breadcrumb.Item>
        </Breadcrumb>
      }
    >
      <Form
        // name="basic"
        initialValues={{ status: -1 }}
        onFinish={onFinish}
        // onFinishFailed={onFinishFailed}
        // autoComplete="off"
      >
        <Form.Item label="状态:" name="status">
          <Radio.Group>
            <Radio value={-1}>全部</Radio>
            <Radio value={0}>草稿</Radio>
            <Radio value={1}>待审核</Radio>
            <Radio value={2}>审核通过</Radio>
            <Radio value={3}>审核失败</Radio>
          </Radio.Group>
        </Form.Item>

        {/* <Form.Item label="频道:" name="channel_id">
          <Select style={{ width: 200 }} placeholder="请选择频道">
            <Option>全部</Option>
            {channels.map((item) => (
              <Option key={item.id} value={item.id}>
                {item.name}
              </Option>
            ))}
          </Select>
        </Form.Item> */}

        {/* 使用封装的 频道 组件*/}
        <Form.Item label="频道:" name="channel_id">
          {/* 解决接收不到参数的问题,在组件内接收 Form.Item组件内部 传给子组件Channel的props */}
          <Channel></Channel>
        </Form.Item>

        <Form.Item label="日期:" name="date">
          <RangePicker />
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit">
            筛选
          </Button>
        </Form.Item>
      </Form>
      <p>根据筛选条件共查询到 {articleDist.total_count} 条结果：</p>
      <Table
        columns={columns}
        dataSource={articleDist.results}
        rowKey="id" //设置key值
        pagination={{
          onChange: handlePageChange,
          position: ['bottomCenter'],
          current: articleDist.page,
          pageSize: articleDist.per_page,
          total: articleDist.total_count,
        }}

        // scroll={{ y: 300 }}
      />
      {/* dataSource=
      {articleDist.map((item) => ({
        ...item,
        key: item.id,
      }))} */}
    </Card>
  );
}
